import json
import os

DATA_FILE = "data/students.json"


def load_data():
    """加载已有数据"""
    if not os.path.exists(DATA_FILE):
        return []
    with open(DATA_FILE, 'r', encoding='utf-8') as f:
        return json.load(f)


def save_data(students):
    """保存数据到文件"""
    # 确保目录存在
    os.makedirs(os.path.dirname(DATA_FILE), exist_ok=True)  # 新增代码
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(students, f, indent=4)


def add_student():
    """添加学生信息"""
    students = load_data()
    student = {
        "学号": input("请输入学号："),
        "姓名": input("请输入姓名："),
        "数学": float(input("数学成绩：")),
        "语文": float(input("语文成绩：")),
        "英语": float(input("英语成绩："))
    }
    students.append(student)
    save_data(students)
    print("添加成功！")


def search_student():
    """按学号/姓名查询"""
    students = load_data()
    keyword = input("请输入学号或姓名：").strip()
    results = [
        s for s in students
        if keyword == s["学号"] or keyword == s["姓名"]
    ]

    if not results:
        print("未找到匹配记录")
        return

    for s in results:
        print(f"学号：{s['学号']} 姓名：{s['姓名']}")
        print(f"数学：{s['数学']} 语文：{s['语文']} 英语：{s['英语']}")
        print(f"总分：{sum([s['数学'], s['语文'], s['英语']]):.1f}\n")


def calculate_statistics():
    """统计班级成绩"""
    students = load_data()
    if not students:
        print("暂无数据")
        return

    # 计算统计值
    math_scores = [s["数学"] for s in students]
    chinese_scores = [s["语文"] for s in students]
    english_scores = [s["英语"] for s in students]

    stats = {
        "数学平均分": sum(math_scores) / len(math_scores),
        "语文最高分": max(chinese_scores),
        "英语最低分": min(english_scores)
    }

    print("=== 班级统计 ===")
    for k, v in stats.items():
        print(f"{k}: {v:.1f}")